/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import modelBanco.ParUsuarios;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import service.LoginService;

/**
 *
 * @author cesar
 */
public class LoginController extends SimpleFormController {
    
    private LoginService loginService;

    public void setLoginService(LoginService loginService) {
        this.loginService = loginService;
    }
    
    public LoginController() {
        //Initialize controller properties here or 
        //in the Web Application Context

        setCommandClass(String.class);
        setCommandName("login");
        setSuccessView("LoginView");
        setFormView("LoginView");
    }
    
    /**
     *
     * @param request
     * @param response
     * @param command
     * @param errors
     * @return
     * @throws Exception
     */
    @Override
    protected ModelAndView onSubmit(
            HttpServletRequest request,
            HttpServletResponse response,
            Object command,
            BindException errors) throws Exception {
        
        String nomeUsuario = (String) request.getParameter("nome_usuario");
        String senhaUsuario = (String) request.getParameter("senha_usuario");
        
        ParUsuarios usuario = loginService.buscarUsuario(nomeUsuario, senhaUsuario);
        
        ModelAndView mv;
        
        if(usuario != null){
         
            mv = new ModelAndView("PrincipalView");
            
        }else{
            
            mv = new ModelAndView("LoginView");
            
            mv.addObject("Mensagem", "Usuário/senha inválidos!");
            
        }
        
        return mv;
        
    }
}
